import tkinter
import os
import random
from platform import system
import ttkbootstrap as ttk

'''
猫咪桌宠
'''
class cat:
    def __init__(self,main):
        self.main=main
        self.delay = 200 # delay in ms
        self.pixels_from_right = 200 # change to move the pet's starting position
        self.pixels_from_bottom = 200 # change to move the pet's starting position
        self.move_speed = 6 # change how fast the pet moves in pixels
        self.state=True
        
        self.root = ttk.Toplevel(self.main.win)
        # initialize frame arrays
        self.animation = dict(
            idle = [tkinter.PhotoImage(file=self.main.path+'/gifs/idle.gif', format = 'gif -index %i' % i) for i in range(5)],
            idle_to_sleep = [tkinter.PhotoImage(file=self.main.path+'/gifs/idle-to-sleep.gif', format = 'gif -index %i' % i) for i in range(8)],
            sleep = [tkinter.PhotoImage(file=self.main.path+'/gifs/sleep.gif', format = 'gif -index %i' % i) for i in range(3)]*3,
            sleep_to_idle = [tkinter.PhotoImage(file=self.main.path+'/gifs/sleep-to-idle.gif', format = 'gif -index %i' % i) for i in range(8)],
            walk_left = [tkinter.PhotoImage(file=self.main.path+'/gifs/walk-left.gif', format = 'gif -index %i' % i) for i in range(8)],
            walk_right = [tkinter.PhotoImage(file=self.main.path+'/gifs/walk-right.gif',format = 'gif -index %i' % i) for i in range(8)]
        )
        self.quit()

        # window configuration
        self.root.overrideredirect(True) # remove UI
        if system() == 'Windows':
            self.root.wm_attributes('-transparent','black')
        else: # platform is Mac/Linux
            # https://stackoverflow.com/questions/19080499/transparent-background-in-a-tkinter-window
            self.root.wm_attributes('-transparent', True) # do this for mac, but the bg stays black
            self.root.config(bg='systemTransparent')
        
        self.root.attributes('-topmost', True) # put window on top
        # self.root.bind("<Button-1>", self.onLeftClick) # 左键打印

        self.root.bind("<Button-2>", self.onRightClick)  # 右键关闭窗口
        self.root.bind('<Double-1>',self.openWin) #双击 打开窗
        self.root.bind("<Button-3>", self.onRightClick) # 中键关闭窗口
        self.root.bind("<Key>", self.onKeyPress) # 监听键盘 q 或 Q 关闭猫咪

        self.root.bind("<ButtonPress-1>", self.StartMove) #监听左键按下操作响应函数
        self.root.bind("<ButtonRelease-1>", self.StopMove) #监听左键松开操作响应函数
        self.root.bind("<B1-Motion>", self.OnMotion)   #监听鼠标移动操作响应函数

        self.label = tkinter.Label(self.root,bd=0,bg='black') # borderless window
        if system() != 'Windows':
            self.label.config(bg='systemTransparent')
        self.label.pack()

        # 左键点击有提示
        # self.menu = tkinter.Menu(self.root)
        # self.menu.add_cascade(label = '别点我，小心我会哭的呦')
        # self.showPopoutMenu()
        
        screen_width = self.root.winfo_screenwidth() # width of the entire screen
        screen_height = self.root.winfo_screenheight() # height of the entire screen
        self.min_width = 10 # do not let the pet move beyond this point
        self.max_width = screen_width-110 # do not let the pet move beyond this point
        
        # change starting properties of the window
        self.curr_width = screen_width-self.pixels_from_right
        self.curr_height = screen_height-self.pixels_from_bottom
        self.root.geometry('%dx%d+%d+%d' % (100, 100, self.curr_width, self.curr_height))

        self.run_cat(0, 'idle')

        # 关闭自动显示
        # self.show()
        self.run()
    
    # 左键点击有问题提示，效果不理想，不考虑使用
    def showPopoutMenu(self):
        def popout(event):
            self.menu.post(event.x + self.label.winfo_rootx(), event.y + self.label.winfo_rooty()-80) 
            self.label.update() 
        self.label.bind('<Button-1>', popout)

    #-------窗口移动-------
    def StartMove(self,event):
        global x, y
        x = event.x
        y = event.y
    
    def StopMove(self,event):
        global x, y
        x = None
        y = None
    
    def OnMotion(self,event):
        global x, y
        deltax = event.x - x
        deltay = event.y - y
        self.root.geometry("+%s+%s" % (self.root.winfo_x() + deltax, self.root.winfo_y() + deltay))

        self.root.update()
        self.curr_width = self.root.winfo_x() + deltax
        self.curr_height = self.root.winfo_y() + deltay

    def update(self, i, curr_animation):
        if self.state:
            # print("Curently: %s" % curr_animation)
            animation_arr=self.run_cat(i,curr_animation)
            
            i += 1
            if i == len(animation_arr):
                # reached end of this animation, decide on the next animation
                next_animation = self.getNextAnimation(curr_animation)
                self.root.after(self.delay, self.update, 0, next_animation)
            else:
                self.root.after(self.delay, self.update, i, curr_animation)

        else:
            self.root.after(self.delay, self.update, i, curr_animation)

    def run_cat(self,i,curr_animation):
        self.root.attributes('-topmost', True) # put window on top
        animation_arr = self.animation[curr_animation]
        frame = animation_arr[i]
        self.label.configure(image=frame)
        
        # move the pet if needed
        if curr_animation in ('walk_left', 'walk_right'):
            self.move_window(curr_animation)
        return animation_arr
           


    def onLeftClick(self, event):
        print("detected left click")
    
    
    def onRightClick(self, event):
        self.quit()

    def openWin(self,event):
        self.main._show()

    def onKeyPress(self, event):
        if event.char in ('q', 'Q'):
            self.quit()
    
    
    def move_window(self, curr_animation):
        if curr_animation == 'walk_left':
            if self.curr_width > self.min_width:
                self.curr_width -= self.move_speed
            
        elif curr_animation == 'walk_right':
            if self.curr_width < self.max_width:
                self.curr_width += self.move_speed

        self.root.geometry('%dx%d+%d+%d' % (100, 100, self.curr_width, self.curr_height))
        self.root.update()
    

    def getNextAnimation(self, curr_animation):
        if curr_animation == 'idle':
            return random.choice(['idle', 'idle_to_sleep', 'walk_left', 'walk_right'])
        elif curr_animation == 'idle_to_sleep':
            return 'sleep'
        elif curr_animation == 'sleep':
            return random.choice(['sleep', 'sleep_to_idle'])
        elif curr_animation == 'sleep_to_idle':
            return 'idle'
        elif curr_animation == 'walk_left':
            return random.choice(['idle', 'walk_left', 'walk_right'])
        elif curr_animation == 'walk_right':
            return random.choice(['idle', 'walk_left', 'walk_right'])
         
    
    def run(self):
        self.root.after(self.delay, self.update, 0, 'idle') # start on idle
        # self.root.mainloop()
    
    def change(self):
        if self.state:
            self.quit()
        else:
            self.show()

    def _quit(self):
        self.state=False
        self.root.destroy()
        
    def show(self):
        self.root.deiconify()
        self.state=True

    def quit(self):
        self.root.withdraw() #隐藏
        self.state=False


